import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/login.vue')
    },
    {
      component: () => import('@/views/main/index.vue'),
      children: [
        {
          path: '/userAdmin',
          name: 'userAdmin',
          meta: {
            title: '用户管理',
            parents: []
          },
          component: () => import('@/views/main/userAdmin/index.vue')
        },
        {
          path: '/sensationAdmin',
          name: 'sensationAdmin',
          meta: {
            title: '红人管理',
            parents: []
          },
          component: () => import('@/views/main/sensationAdmin/index.vue')
        },
        {
          path: '/memberAdmin',
          name: 'memberAdmin',
          meta: {
            title: '权益管理',
            parents: []
          },
          component: () => import('@/views/main/memberAdmin/index.vue')
        },
        {
          path: '/memberDetail',
          name: 'memberDetail',
          meta: {
            title: '权益详情',
            parents: [
              {
                title: '权益管理',
                path: '/memberAdmin'
              }
            ]
          },
          component: () => import('@/views/main/memberAdmin/detail.vue')
        }
      ]
    }
  ]
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (!token && to.path !== '/login') {
    next('/login');
  } else if (token && ['/', '/login'].some(item => item === to.path)) {
    next('/userAdmin');
  } else {
    next()
  }
})

export default router;
